package com.sl.au.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.sl.au.entity.Account;
import com.sl.au.entity.ArchiveInfo;
import com.sl.au.entity.ArchiveReportInfo;
import com.sl.au.entity.BussinessContent;
import com.sl.au.entity.Comment;
import com.sl.au.entity.Division;
import com.sl.au.entity.EventRegister;
import com.sl.au.entity.EventReport;
import com.sl.au.entity.EventType;
import com.sl.au.entity.GridAreaInfo;
import com.sl.au.entity.Module;
import com.sl.au.entity.News;
import com.sl.au.entity.Option;
import com.sl.au.entity.Role;
import com.sl.au.entity.User;
import com.sl.au.entity.MessageVerification;
import com.sl.au.repository.MessageVerificationRepository;
import com.sl.au.service.ArchiveInfoService;
import com.sl.au.service.ArchiveReportInfoService;
import com.sl.au.service.BussinessContentService;
import com.sl.au.service.CommentService;
import com.sl.au.service.EventRegisterService;
import com.sl.au.service.EventReportService;
import com.sl.au.service.EventTypeService;
import com.sl.au.service.GridAreaInfoService;
import com.sl.au.service.ModuleService;
import com.sl.au.service.NewsService;
import com.sl.au.service.OperateLogService;
import com.sl.au.service.OptionService;
import com.sl.au.service.RoleService;
import com.sl.au.service.UserService;
import com.sl.utils.ExdeUtil;

@RestController
@RequestMapping(value = "/ui/mobileMain")
public class MobileMainController extends BaseController {

	@Autowired
	private OptionService optionService;
	@Autowired
	private GridAreaInfoService gridAreaInfoService;
	@Autowired
	private BussinessContentService bussinessContentService;
	@Autowired
	private EventReportService eventReportService;
	@Autowired
	private NewsService newsService;
	@Autowired
	private CommentService commentService;
	@Autowired
	private ArchiveReportInfoService archiveReportInfoSerivce;
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	OperateLogService operateLogService;
	@Autowired
	EventTypeService eventTypeService;
	@Autowired
	ModuleService moduleService;
	@Autowired
	MessageVerificationRepository messageVerificationRepository;
	@Autowired
	ArchiveInfoService archiveInfoService;
	@Autowired
	EventRegisterService	eventRegisterService;
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index(ModelAndView modelAndView, HttpServletRequest request) {
		String device = request.getParameter("device");
		String identify = request.getParameter("identify");
		List<Option> accusationTypes = optionService.getRepository().findByGroup("举报类型");
		modelAndView.setViewName("mobile/mobileMain");
		modelAndView.addObject("identify", identify);
		modelAndView.addObject("accusationTypes", accusationTypes);
		Account account =this.getMyAccount();
		for (Module m : account.getRole().getModules()) {
			if(m.getModuleName().equals("我的"))
			{
				modelAndView.addObject("historyUrl",m.getTarget()+"&device=mobile&identify=");
				break;
			}
		}
		return modelAndView;
	}

	@RequestMapping(value = "register", method = RequestMethod.GET)
	public ModelAndView register(ModelAndView modelAndView, HttpServletRequest request) {
		String device = request.getParameter("device");
		String identify = request.getParameter("identify");
		modelAndView.setViewName("mobile/mobileRegister");
		modelAndView.addObject("identify", identify);
		return modelAndView;
	}

	@RequestMapping(value = "registerUser", method = RequestMethod.POST)
	public Map<String, Object> registerUser(HttpServletRequest request, @RequestBody Map<String, Object> models) {
		Map<String, Object> map = new HashMap<String, Object>();
		User user = JSON.parseObject(JSON.toJSONString(models.get("user")), User.class);
		Account account = JSON.parseObject(JSON.toJSONString(models.get("account")), Account.class);
		MessageVerification messageVerification = JSON.parseObject(JSON.toJSONString(models.get("messageVerification")), MessageVerification.class);
		int code = 0;

		User userOne = userService.getRepository().findByContactType(user.getContactType());
		Account accountOne = this.accountService.getRepository().findByAccountName(account.getAccountName());
		if (userOne != null) {
			code = 98;
			map.put("code", code);
			map.put("msg", "电话号已存在!");
			return map;
		}
		
		MessageVerification messageVerificationTemp =this.messageVerificationRepository.findByPhone(messageVerification.getPhoneNum());
		if(messageVerificationTemp==null){
			code = 98;
			map.put("code", code);
			map.put("msg", "未获取验证码!");
			return map;
		}else{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			 long d1 = messageVerificationTemp.getUpdateTime().getTime();
		     long d2 = DateTime.now().getMillis();
		     int d = (int) (Math.abs(d1-d2) / (1000 * 60));
		     int interval=30;//分钟
		     Option intervalOp= this.optionService.getRepository().findByTitleAndGroup("验证码超时", "超时时限");
		     if(intervalOp!=null)
		     {
		    	 try{
		    		 interval =(int)(Double.parseDouble(intervalOp.getValue())*60);
		    	 }catch(Exception ex){
		    	 }
		     }
		     if(d>interval){
		    	 code = 98;
					map.put("code", code);
					map.put("msg", "验证码超时!");
					return map;
		     }else if(!messageVerification.getPhoneVerification().equals(messageVerificationTemp.getPhoneVerification())){
		    	 code = 98;
					map.put("code", code);
					map.put("msg", "验证码错误!");
					return map;
		     }
		}
		if (accountOne == null) {
			userService.saveUser(user);
			Role role = roleService.getRepository().findByName("游客");
			User registerUser = userService.getRepository().findOne(user.getId());
			account.setRole(role);
			account.setUser(registerUser);
			accountService.getRepository().save(account);

			// map.put("modules",
			// moduleService.getSimpleModulesByRole(role.getId()));
			// map.put("user", registerUser);
			// map.put("accountId", account.getId());
			// map.put("userId", registerUser.getId());

			HttpSession session = request.getSession();
			session.setAttribute("account", account);

			map.put("code", 1);
			operateLogService.log(registerUser, "登录系统", "登录成功");
			map.put("msg", "注册成功！");
		} else {
			code = 99;
			map.put("code", code);
			map.put("msg", "用户名已存在!");
		}

		return map;
	}

	@RequestMapping(value = "/getContent", method = RequestMethod.GET)
	public Map<String, Object> getOne() {
		Map<String, Object> map = new HashMap<String, Object>();
		double longitude = ExdeUtil.str2double((String) request.getParameter("lng"));
		double latitude = ExdeUtil.str2double((String) request.getParameter("lat"));
		GridAreaInfo gridAreaInfo = gridAreaInfoService.GetGridAreaInfoByCoordinate(longitude, latitude);
		if (gridAreaInfo == null) {
			map.put("code", 0);
			return map;
		}
		map.put("manager", gridAreaInfo.getUsers());
		Division division = gridAreaInfo.getDivision();
		if (division != null) {
			BussinessContent bussinessContent = bussinessContentService.getRepository().findByDivision(division);
			if (bussinessContent != null) {
				map.put("code", 1);
				map.put("content", bussinessContent);
			} else {
				map.put("code", 0);
			}
		} else {
			map.put("code", 0);
		}
		return map;
	}

	@RequestMapping("/findReportById/{id}")
	public Map<String, Object> findReportById(@PathVariable("id") String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		EventReport eventReport = eventReportService.getRepository().findOne(id);
		ArchiveReportInfo archiveReportInfo = archiveReportInfoSerivce.getRepository().getByReport(eventReport);
		List<EventRegister> registers = eventRegisterService.findByReportId(id);
		List<ArchiveInfo> archiveInfos = new ArrayList<ArchiveInfo>();
		for(EventRegister register : registers) {
			ArchiveInfo info = archiveInfoService.getRepository().findOneArchiveByRegisterId(register.getId());
			if(info != null) {
				archiveInfos.add(info);
			}
		}
//		ArchiveInfo archiveInfo = archiveInfoService.getRepository()
		List<Comment> comments = commentService.getRepository().findCommentByEventReportId(id);
		map.put("report", eventReport);
		map.put("comments", comments);
		map.put("archive", archiveReportInfo);
		map.put("archiveInfos", archiveInfos);
		return map;
	}

	@RequestMapping("/findNewsById/{id}")
	public Map<String, Object> findNewsById(@PathVariable("id") String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		News news = newsService.getRepository().findOne(id);
		map.put("news", news);
		return map;
	}

	@RequestMapping("/getListEvents")
	public Map<String, Object> getListEvents() {
		Map<String, Object> map = new HashMap<String, Object>();
		List<EventReport> EventReports = eventReportService.getPageByEventVariable(0, 10, "", "已归档", "createTime",
				Sort.Direction.DESC);
		map.put("events", EventReports);
		map.put("code", 1);
		return map;
	}

	@RequestMapping("/getListNews")
	public Map<String, Object> getListNews() {
		Map<String, Object> map = new HashMap<String, Object>();
		List<News> news = newsService.getNewsByKey(0, 10, "", null, null);
		map.put("news", news);
		map.put("code", 1);
		return map;
	}

	@RequestMapping("/getData")
	public Map<String, Object> getData() {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Module> modules = moduleService.getRepository().findModulesMenu3(this.getMyAccount().getRole().getId(),"wcsi");
		// map.put("modules", this.getMyAccount().getRole().getModules());
		map.put("modules", modules);
		List<EventType> eventTypes = eventTypeService.getRepository().getMobileEventTypesByParent("0");
		map.put("eventTypes", eventTypes);
		return map;
	}
	
	@RequestMapping("/getDcmsApp")
	public Map<String, Object> getDcmsApp() {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Module> modules = moduleService.getRepository().findModulesMenu3(this.getMyAccount().getRole().getId(),"dcms");
		// map.put("modules", this.getMyAccount().getRole().getModules());
		map.put("modules", modules);
		return map;
	}

	@RequestMapping("/saveComment")
	public Map<String, Object> saveComment(@RequestBody Comment comment) {
		Map<String, Object> map = new HashMap<String, Object>();
		EventReport eventReport = eventReportService.getRepository().findOne(comment.getEventReport().getId());
		User user = this.getMyAccount().getUser();
		comment.setCommentator(user);
		comment.setEventReport(eventReport);
		comment.setOperator(user);

		commentService.saveComment(comment);

		map.put("code", 1);
		return map;
	}

	@RequestMapping("/sendCodeByPhone/{phone}")
	public Map<String, Object> sendCodeByPhone(@PathVariable("phone") String phone) {
		Map<String, Object> map = new HashMap<String, Object>();
		String verification = "";
		Random random = new Random();
		for (int i = 0; i < 6; i++) {
			verification += random.nextInt(10);
		}
		String content = "【悦来城市综合服务平台】验证码:" + verification;
			Option op = this.optionService.findByGroupAndExtended1("通知短信格式","注册验证码");
			if (op!= null) {
				content = op.getTitle();
			}
			content=content.replace("{0}", verification);
		map=this.sendMessage(phone, content);
		if(map!=null&&map.get("code")!=null&&map.get("code").equals(1)){
			MessageVerification messageVerification=this.messageVerificationRepository.findByPhone(phone);
			if(messageVerification==null){
				messageVerification=new MessageVerification();
				messageVerification.setPhoneNum(phone);
			}
			messageVerification.setPhoneVerification(verification);
			messageVerification.setUpdateTime(DateTime.now().toDate());
			this.messageVerificationRepository.save(messageVerification);
		}
		return map;
	}
}
